#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
多房间实时传感器数据生成器统一管理器
同时管理Room_1、Room_2、Room_3的数据生成
"""

import time
import threading
import signal
import sys
import os
from datetime import datetime

# 导入各个房间的数据生成器
try:
    from realtime_data_generator_room1 import RealtimeDataGeneratorRoom1
    from realtime_data_generator_room2 import RealtimeDataGeneratorRoom2
    from realtime_data_generator_room3 import RealtimeDataGeneratorRoom3
except ImportError:
    print("❌ 无法导入房间数据生成器模块，请确保文件存在")
    sys.exit(1)

class MultiRoomDataGenerator:
    """多房间数据生成器管理器"""
    
    def __init__(self):
        """初始化多房间管理器"""
        self.generators = {}
        self.is_running = False
        self.status_thread = None
        
        print("🏢 初始化多房间数据生成器管理器")
        
        # 初始化各个房间的生成器
        try:
            self.generators['Room_1'] = RealtimeDataGeneratorRoom1()
            print("✅ Room_1 生成器初始化完成")
        except Exception as e:
            print(f"❌ Room_1 生成器初始化失败: {e}")
        
        try:
            self.generators['Room_2'] = RealtimeDataGeneratorRoom2()
            print("✅ Room_2 生成器初始化完成")
        except Exception as e:
            print(f"❌ Room_2 生成器初始化失败: {e}")
        
        try:
            self.generators['Room_3'] = RealtimeDataGeneratorRoom3()
            print("✅ Room_3 生成器初始化完成")
        except Exception as e:
            print(f"❌ Room_3 生成器初始化失败: {e}")
        
        if not self.generators:
            print("❌ 没有可用的房间生成器")
            sys.exit(1)
        
        print(f"🎯 成功初始化 {len(self.generators)} 个房间的数据生成器")
    
    def start_all(self):
        """启动所有房间的数据生成器"""
        if self.is_running:
            print("⚠️  多房间数据生成器已在运行中")
            return
        
        print("=" * 80)
        print("🚀 启动多房间实时传感器数据生成系统")
        print("=" * 80)
        print(f"📅 启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"🏠 管理房间数量: {len(self.generators)}")
        print("=" * 80)
        
        self.is_running = True
        
        # 启动所有房间的生成器
        success_count = 0
        for room_id, generator in self.generators.items():
            try:
                print(f"\n🔄 启动 {room_id} 数据生成器...")
                generator.start()
                success_count += 1
                print(f"✅ {room_id} 数据生成器启动成功")
                time.sleep(2)  # 避免同时启动造成冲突
            except Exception as e:
                print(f"❌ {room_id} 数据生成器启动失败: {e}")
        
        if success_count == 0:
            print("❌ 所有房间数据生成器启动失败")
            self.is_running = False
            return
        
        print(f"\n🎉 成功启动 {success_count}/{len(self.generators)} 个房间的数据生成器")
        
        # 启动状态监控线程
        self.status_thread = threading.Thread(target=self.status_monitor_loop, daemon=True)
        self.status_thread.start()
        
        print("\n📊 系统状态监控已启动")
        print("🔄 所有房间数据生成中... (按 Ctrl+C 停止)")
    
    def stop_all(self):
        """停止所有房间的数据生成器"""
        if not self.is_running:
            print("⚠️  多房间数据生成器未在运行")
            return
        
        print("\n" + "=" * 60)
        print("🛑 正在停止多房间数据生成系统...")
        print("=" * 60)
        
        self.is_running = False
        
        # 停止所有房间的生成器
        for room_id, generator in self.generators.items():
            try:
                print(f"🛑 停止 {room_id} 数据生成器...")
                generator.stop()
                print(f"✅ {room_id} 数据生成器已停止")
            except Exception as e:
                print(f"❌ 停止 {room_id} 数据生成器失败: {e}")
        
        # 等待状态监控线程结束
        if self.status_thread and self.status_thread.is_alive():
            self.status_thread.join(timeout=5)
        
        print("\n✅ 所有房间数据生成器已停止")
        print("👋 多房间数据生成系统已退出")
    
    def status_monitor_loop(self):
        """状态监控循环"""
        print("📈 状态监控线程已启动")
        
        while self.is_running:
            try:
                # 每60秒打印一次状态报告
                time.sleep(60)
                
                if not self.is_running:
                    break
                
                self.print_status_report()
                
            except Exception as e:
                print(f"❌ 状态监控出错: {e}")
                time.sleep(10)
    
    def print_status_report(self):
        """打印状态报告"""
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        print("\n" + "=" * 60)
        print(f"📊 多房间数据生成系统状态报告 - {current_time}")
        print("=" * 60)
        
        for room_id, generator in self.generators.items():
            status = "🟢 运行中" if generator.is_running else "🔴 已停止"
            output_file = generator.output_file
            json_file = generator.json_file
            
            # 检查文件是否存在和大小
            csv_status = "❌ 不存在"
            json_status = "❌ 不存在"
            
            try:
                if os.path.exists(output_file):
                    size = os.path.getsize(output_file)
                    csv_status = f"✅ {size/1024:.1f}KB"
            except:
                pass
            
            try:
                if os.path.exists(json_file):
                    json_status = "✅ 存在"
            except:
                pass
            
            print(f"🏠 {room_id:8} | {status:8} | CSV: {csv_status:12} | JSON: {json_status}")
        
        print("=" * 60)
        print("💡 提示: 数据文件位置:")
        for room_id in self.generators.keys():
            print(f"   {room_id}: data/{room_id}/realtime_sensor_data.csv")
        print("=" * 60)
    
    def get_room_status(self, room_id):
        """获取指定房间的状态"""
        if room_id not in self.generators:
            return None
        
        generator = self.generators[room_id]
        return {
            'room_id': room_id,
            'is_running': generator.is_running,
            'output_file': generator.output_file,
            'json_file': generator.json_file,
            'csv_exists': os.path.exists(generator.output_file),
            'json_exists': os.path.exists(generator.json_file)
        }
    
    def restart_room(self, room_id):
        """重启指定房间的数据生成器"""
        if room_id not in self.generators:
            print(f"❌ 房间 {room_id} 不存在")
            return False
        
        try:
            generator = self.generators[room_id]
            print(f"🔄 重启 {room_id} 数据生成器...")
            
            # 停止
            if generator.is_running:
                generator.stop()
                time.sleep(2)
            
            # 重新启动
            generator.start()
            print(f"✅ {room_id} 数据生成器重启成功")
            return True
            
        except Exception as e:
            print(f"❌ {room_id} 数据生成器重启失败: {e}")
            return False

def signal_handler(signum, frame):
    """信号处理器"""
    print(f"\n⚠️  收到信号 {signum}")
    if 'multi_generator' in globals():
        multi_generator.stop_all()
    sys.exit(0)

def main():
    """主函数"""
    global multi_generator
    
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    try:
        # 创建多房间管理器
        multi_generator = MultiRoomDataGenerator()
        
        # 启动所有房间的数据生成器
        multi_generator.start_all()
        
        # 保持主线程运行
        while multi_generator.is_running:
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n⚠️  收到停止信号...")
        if 'multi_generator' in locals():
            multi_generator.stop_all()
    except Exception as e:
        print(f"❌ 系统运行出错: {e}")
        if 'multi_generator' in locals():
            multi_generator.stop_all()
    finally:
        print("👋 程序已退出")

if __name__ == "__main__":
    main() 